package kotlincode

import kotlinx.coroutines.*
import java.util.concurrent.Executors
import kotlin.coroutines.coroutineContext


fun main() {
//    coroutineContext1()
//    coroutineContext2()
    coroutineContext3()
}

fun coroutineContext1() = runBlocking {
    val user = getUserInfo1()
    logX(user)
}

suspend fun getUserInfo1(): String {
    logX("Before IO Context.")
    withContext(Dispatchers.IO) {
        logX("In IO Context.")
        delay(1000L)
    }
    logX("After IO Context.")
    return "BoyCoder"
}

val mySingleDispatcher = Executors.newSingleThreadExecutor {
    Thread(it, "MySingleThread").apply { isDaemon = true }
}.asCoroutineDispatcher()

@OptIn(ExperimentalStdlibApi::class)
fun coroutineContext2() = runBlocking {
    val scope = CoroutineScope(Job() + mySingleDispatcher)
    // 注意这里
    scope.launch(CoroutineName("MyFirstCoroutine!")) {
        logX(coroutineContext[CoroutineDispatcher] == mySingleDispatcher)
        delay(1000L)
        logX("First end!")
    }

    delay(500L)
    scope.cancel()
    delay(1000L)
}

suspend fun testContext() = coroutineContext


fun coroutineContext3() = runBlocking {
    println(testContext())
}